<?php

App::uses('CakeEmail', 'Network/Email');
App::uses('Sanitize', 'Utility');

class ContactformController extends AppController {

    public $helpers = array('Form');
    public $components = array('Email', 'Auth');

    public $uses = array('Contactform.Contactform');

    public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('show');
		$this->cacheAction = false;
    }
    
    public function beforeRender(){
    	parent::beforeRender();
    }

    public function show() {
		if($this->request->is('post')) {
		    $email = new CakeEmail();
		    try {
	    	    $email->config('smtp');
		    } catch(Exception $e) {
	    	    echo 'Config in email.php not found';
	    	    exit;
		    }
	
		    $this->Contactform->set($this->request->data['Contactform']);
	
		    if($this->Contactform->validates()) {
			$data = $this->request->data['Contactform'];
	
			$email->to(Sanitize::clean(Configure::read('cfg.contact_form_email')))
			  ->replyTo(Sanitize::clean($data['Mail']))
			  ->subject(__d('contactform', 'contact form request'))
			  ->send(
				  __d('contactform', 'imię i nazwusko').': '.Sanitize::clean($data['Name'])."\n\r".
				  __d('contactform', 'email').': '.Sanitize::clean($data['Mail'])."\n\n\r".
				  __d('contactform', 'telefon').': '.Sanitize::clean($data['Telefon'])."\n\n\r".
				  __d('contactform', 'message').":\n\r".
				  Sanitize::html($data['Message'])."\n\n\r".
				  "----------------------------\n\r".
				  __d('contactform', 'sent from').' '.Router::url('/', true)
			    );
	
			
			$conditions['conditions']['Template.slug'] = 'dziekujemy_za_wyslanie_wiadomosci_kontaktowej';
			$username = $data['Name'];
			$content_ = $this->Templates->parse($conditions, array(
					'imie_nazwisko'=>$username));
			
			
			if(is_array($content_)){
				try {
					$content = $content_['Template']['content'];
					$subject = $content_['Template']['subject'];
						
			
					$email->to(Sanitize::clean($data['Mail']))
					->subject($subject)
					->send($content);
			
				} catch(Exception $e) {
					echo $e->getMessage();
					exit;
				}
			}
			
// 			$email->to(Sanitize::clean($data['Mail']))
// 				->subject(__d('contactform', 'potwierdzenie wysłania wiadomości'))
// 				->send(
// 					__d('contactform', 'Witaj').' '.Sanitize::clean($data['Name'])."\n".
// 					__d('contactform', 'Bardzo dziękujemy za wiadomość wysłaną z strony ').Router::url('/', true)
							  
// 				);
			
			$this->Session->setFlash(__d('contactform', '<script>alert("Wiadomość wysłana pomyślnie")</script>'), '', array('status' => 'success'));
			$this->redirect($this->referer());
		    } else {
			// throw errors from model
		    }
	
		}
	
		$this->set('title_for_layout', __d('contactform', 'contact form'));
		$this->articles();
    }

}